package com.ftg.learn.controller;

import com.ftg.learn.util.AudioCryptoUtil;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@RestController
@RequestMapping("/test")
public class TestController {


    @PostMapping("/upload")
    public ResponseEntity<String> uploadAudio(@RequestParam("file") MultipartFile file) {
        try {
            Path tempFile = Files.createTempFile("upload-", ".tmp");
            file.transferTo(tempFile);

            Path encryptedFile = Paths.get("encrypted", file.getOriginalFilename() + ".enc");
            Files.createDirectories(encryptedFile.getParent());
            AudioCryptoUtil.encryptFile(tempFile, encryptedFile, "your-secret-password");

            String desktopPath = System.getProperty("user.home") + "\\Desktop\\";
            Path desktopEncryptedFile = Paths.get(desktopPath, file.getOriginalFilename() + ".enc");
            Files.copy(encryptedFile, desktopEncryptedFile);

            Files.delete(tempFile);
            return ResponseEntity.ok("上传并加密成功");
        } catch (Exception e) {
            return ResponseEntity.status(500).body("加密失败: " + e.getMessage());
        }
    }

    @GetMapping("/play/{filename}")
    public void playAudio(@PathVariable String filename, HttpServletResponse response) throws Exception {
        Path encryptedFile = Paths.get("encrypted", filename + ".enc");
        if (!Files.exists(encryptedFile)) {
            response.sendError(404, "文件不存在");
            return;
        }

        byte[] decryptedBytes = AudioCryptoUtil.decryptFileToBytes(encryptedFile, "your-secret-password");

        response.setContentType("audio/mpeg"); // 根据实际格式调整
        response.setContentLength(decryptedBytes.length);
        response.getOutputStream().write(decryptedBytes);
        response.getOutputStream().flush();
    }
}
